<template>
  <div style="height: 100%; width: 100%">
    <!-- 放大缩小按钮 -->
    <div class="buttonDiv" style="position: absolute; height: 246px; width: 55px; z-index: 1; overflow: hidden; top: 20px">
      <div style="position: absolute; overflow: hidden; height: 99px; width: 33px; left: 10px">
        <button @click="view.setZoom(view.getZoom()+1)" type="button" title="放大">+</button>
        <button @click="view.setZoom(view.getZoom()-1)" type="button" title="缩小">-</button>
      </div>
    </div>
    <!-- 加载底图及鼠标事件 -->
    <div id="map" @contextmenu.prevent="showRMenu">
      <div id="menuDiv" v-show="showMenu">
        <ul id="menu" class="menu">
          <li v-for="(item,index) in this.menuData" @click="clickMenu(item.cd,item.nm)" :key="index">
            {{item.nm}}
          </li>
        </ul>
      </div>
    </div>
    <!-- 选择库场 -->
    <el-dialog :visible.sync="dialogVisible" :title="'选择库场'" width="100%">
      <el-row style="text-align:left">
        <el-form ref="formName" :model="editForm" label-width="50px" :rules="rules">
          <el-form-item label="票货">
            <el-select 
              v-model="editForm.cargoInfoId"
              style="width:100%"
              clearable
              size="mini"
              filterable>
              <el-option
                v-for="item in this.cargoInfoList"
                :key="item.id"
                :label="item.splitBillLabel"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库场" prop="storehouseId">
            <el-select 
              v-model="editForm.storehouseId"
              style="width:100%"
              clearable
              size="mini"
              @change="getLocationAndStackByid"
              filterable>
              <el-option
                v-for="item in this.storehouseList"
                :key="item.id"
                :label="item.storehouseName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货位" prop="locationId">
            <el-select 
              v-model="editForm.locationId"
              style="width:100%"
              @change="getStackPositionByid"
              size="mini"
              clearable
              filterable>
              <el-option
                v-for="item in this.locationList"
                :key="item.id"
                :label="item.locationNo"
                :value="item.locationId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="垛号">
            <el-select 
              v-model="editForm.stackPosition"
              style="width:100%" 
              size="mini"
              clearable
              filterable>
              <el-option
                v-for="item in this.heapList"
                :key="item.id"
                :label="item.stackPosition"
                :value="item.stackPosition">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="dialogVisible = false" size="mini">返回</el-button>
        <el-button type="primary" size="mini" @click.stop="submitDrawer()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 机械弹出框 -->
    <div id="mi_popup" class="mi_ol-popup" :style="miTableStyle">
			<div style="border-bottom: 1px dashed #cccccc; height: 81px; width: 195pxpx; left: 30px; position: absolute; top: 5px">
        <div style="height: 80px; width: 235px; left: -4px; position: absolute; top: 0">
					<span style="left: 0; bottom: 0; top: 20px">机械编号：{{ currentMi.equipmentNo }}</span>
					<span style="left: 144px; bottom: 0; top: 20px">速度：{{ currentMi.speed }}</span>
					<span style="left: 0; bottom: 0; top: 50px">方向：{{ currentMi.derection }}</span>
				</div>
			</div>
		</div>
    <!--垛位弹出框 -->
    <div id="dw_popup" class="dw_ol-popup" :style="dwTableStyle">
			<div style="border-bottom: 1px dashed #cccccc; height: 81px; width: 215pxpx; left: 30px; position: absolute; top: 5px">
        <div style="height: 140px; width: 390px; left: -13px; position: absolute; top: 0">
					<span style="left: 0; bottom: 0; top: 20px">船名航次：{{ dwForm.shipvoyageName }}</span>
					<span style="left: 285px; bottom: 0; top: 20px">货主：{{ dwForm.cargoOwnerName }}</span>
					<span style="left: 0; bottom: 0; top: 50px">货代：{{ dwForm.cargoAgentName }}</span>
          <span style="left: 285px; bottom: 0; top: 50px">货名：{{ dwForm.cargoName }}</span>
          <span style="left: 0; bottom: 0; top: 80px">件数：{{ dwForm.quantity }}</span>
          <span style="left: 285px; bottom: 0; top: 80px">重量：{{ dwForm.ton }}</span>
          <span style="left: 0; bottom: 0; top: 110px">体积：{{ dwForm.volume }}</span>
				</div>
			</div>
		</div>
  </div>
</template>
<script>
import "ol/ol.css";
import { Map, View } from "ol";
import {ImageStatic, XYZ, TileWMS, Vector as VectorSource} from 'ol/source';
import {defaults} from 'ol/control'
import Feature from 'ol/Feature';
import {Polygon} from 'ol/geom';
import {Modify, DoubleClickZoom} from 'ol/interaction';
import OSM from "ol/source/OSM";
import Draw, {createBox} from 'ol/interaction/Draw';
import {Circle as CircleStyle, Fill, Icon, Stroke, Style, Text} from 'ol/style';
import {Image, Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import Overlay from 'ol/Overlay';
import Collection from 'ol/Collection';
import Point from 'ol/geom/Point'
import publicapi from '@/api/public/index'
import api from '@/api/yardTally/shcoordinates/index'
export default {
  data () {
    return {
      map: null, // 底图
      view: null, // 位置视图
      menuData: [], // 右键菜单
      feature: null, // 鼠标选中信息
      showMenu: false, // 是否显示右键菜单
      modify: null,
      dialogVisible: false, // 库场弹框
      editForm: {
        cargoInfoId: '',
        storehouseId: '',
        locationId: '',
        stackPosition: '',
      },
      rules: {
        storehouseId: [{ required: true, message: '请选择库场', trigger: 'change' }],
        stackPosition: [{ required: true, message: '请选择垛号', trigger: 'change' }],
      },
      storehouseList: [], // 库场
      locationList: [], // 货位
      heapList: [], // 垛号
      massLayerHeap: '', // 存在库场
      heapNameList: [], // 用于显示的库场信息
      cargoInfoList: [], // 票货List
      machineList: [], // 机械列表
      miVectorLayer: '', // 机械图层
      machineLogo: '',
      currentMi: {
				equipmentNo: "",
				speed: "",
				derection: "",
			},
      miTableStyle: {
				display: "none",
			},
      dwTableStyle: {
				display: "none",
			},
      dwForm: {
        shipvoyage: '',
        cargoOwnerName: '',
        cargoAgentName: '',
        cargoName: '',
        quantity: '',
        ton: '',
        volume: '',
      },
      times: null,
    }
  },
  watch: {
    "menuData": function (newQuestion, oldQuestion) {
      this.showMenu = newQuestion.length > 0;
    },
    "$route": {
      handler (newV,oldv) {
        var _this = this
        console.log(newV.name)
        if (newV.name != 'shcoordinates') {
          clearInterval(_this.times);
        }
      },
      deep: true
    },
    "$route.params": {
      immediate: true,
      handler(newv, oldv) {
        console.log(newv);
        var _this = this
        if (newv.cargoInfoId) {
          _this.getstorehouseList() // 获取库场
          _this.getDrawerStorehouse() // 获取已绘制库场
          _this.getCargoInfo() // 获取票货信息

          setTimeout(() => {
            _this.editForm.cargoInfoId = this.cargoInfoList.filter(v => v.cargoInfoId == newv.cargoInfoId)[0].id
            _this.editForm.storehouseId = newv.storehouseId
            _this.getLocationAndStackByid(this.editForm.storehouseId)
          },1000)

          _this.dialogVisible = true
        }
      }
    }
  },
  created () {
    this.times = setInterval(() => {
      this.getMachine();
    }, 1000 * 30);
  },
  beforeDestroy() {//销毁
    clearInterval(this.times);
  },
  mounted () {
    this.init() // 初始化地图
    this.initProup()
    this.getstorehouseList() // 获取库场
    this.getDrawerStorehouse() // 获取已绘制库场
    this.getMachine() // 获取机械
    this.getCargoInfo() // 获取票货信息
  },
  methods: {
    // 初始化地图
    init () {
      let bounds = [120.38427, 31.95702, 120.42749, 31.97283];

      // let url = 'http://geo.zjgport.cn:8087/geoserver/wms';
      let layer1 = new TileLayer({
        source: new XYZ(
          {
            url: 'http://t{0-5}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=1a352ee60367cb9ac14fe370d9d3849a',
            isBaseLayer: true,
          }
        ),   //这个会出现底图
      })
      let layer2 = new TileLayer({
        source: new TileWMS({
          ratio: 1,
          params: {
            'service': 'WMS',
            'version': '1.1.0',
            'request': 'GetMap',
            'layers': 'zjg_group',
            'srs': 'EPSG:4326',
            'format': 'application/openlayers',
          },
          // url: url
        }),
        opacity: 0.6,
      })
      this.map = new Map({
        controls: defaults({
          attribution: false
        }),
        target: 'map',
        view: new View({
          projection: 'EPSG:4326',
        })
      });

      // 移除地图DoubleClick放大
      const dblClickInteraction = this.map
        .getInteractions()
        .getArray()
        .find(interaction => {
          return interaction instanceof DoubleClickZoom;
        });
      this.map.removeInteraction(dblClickInteraction);

      this.map.addLayer(layer1)
      this.map.addLayer(layer2);
      this.view = this.map.getView();
      this.view.fit(bounds, this.map.getSize());

      this.view.setZoom(15.5);
      this.view.setCenter([118.51410, 39.11650]);
    },
    // 鼠标右击事件
    showRMenu(e) {
      let pixel = this.map.getEventPixel(e);
      let coordinate = this.map.getEventCoordinate(e);
      let hit = this.map.hasFeatureAtPixel(pixel);//通过像素点判断当前鼠标上是否有图形
      let feature = this.map.forEachFeatureAtPixel(pixel,
        function (feature, style) {
          return feature;
        });
      this.feature = feature
      console.log(feature)

      this.menuData = [];
      // if (this.isQuery === '0') {
        if (!hit) {
          //显示右键菜单
          let menuItem = {cd: 'drawRegion', nm: '绘制区域'};
          this.menuData.push(menuItem)
          this.showMenu = true;
        } else {
          if (feature.get("showType") == "cargoPlace") {
            //显示右键菜单
            let menuItem = {cd: 'clearP', nm: '清除'};
            let edit = {cd: 'edit', nm: '编辑'};
            // this.menuData.push(edit);
            if(this.menuArr.includes('删除货位')){
              this.menuData.push(menuItem)
            }
          }
          if (feature.values_.showType == "storehouse") {
            //显示右键菜单
            let menuItem = {cd: 'clearH', nm: '清除'};
            this.menuData.push(menuItem);
          }
        }
      // }
      let menu_overlay = new Overlay({
        element: document.getElementById("menuDiv"),
        positioning: 'center-center',
        id: "menu"
      });
      menu_overlay.setPosition(coordinate);
      this.map.addOverlay(menu_overlay);
    },
    // 右键菜单点击操作
    clickMenu(menuCd,menuNm) {
      console.log(menuCd)
      console.log(menuNm)
      this.editForm.cargoInfoId = ''
      this.editForm.storehouseId = ''
      this.editForm.locationId = ''
      this.editForm.stackPosition = ''

      if (menuCd == 'drawRegion') {
        this.dialogVisible = true
        if (this.$refs['formName'])
          this.$refs['formName'].resetFields()
      }

      if (menuCd == 'clearH') {
        this.deleteStorehouse()
      }

      let overlayMenu = this.map.getOverlayById("menu");
      if (overlayMenu) {
        overlayMenu.setPosition(undefined);
        overlayMenu = null;
      }
    },
    // 单击事件
    initProup () {
      const _this = this
      let overlay;
      let mi_container = document.getElementById("mi_popup");
      let dw_container = document.getElementById("dw_popup");

      this.map.addEventListener('click', function (evt) {
        let coordinate = evt.coordinate;
        console.log(coordinate)
        _this.showMenu = false

        let feature = this.forEachFeatureAtPixel(evt.pixel, function (feature, style) {
		    	return feature;
		    });
        console.log(feature)
        if (!feature) {
          _this.miTableStyle.display = 'none'
          _this.dwTableStyle.display = 'none'
          return;
        }
        if (feature.values_.showType == "machineInfo") {
					let currentMi = {};
					currentMi.equipmentNo = feature.get("equipmentNo");
					currentMi.speed = feature.get("speed");
					currentMi.derection = feature.get("derection");
					_this.currentMi = currentMi;

					//创建弹出框
					overlay = new Overlay({
						element: mi_container,
					});

          _this.miTableStyle.display = 'block'
					overlay.setPosition(coordinate);
					this.addOverlay(overlay);
				} else if (feature.values_.showType == "storehouse") {
					let dwForm = {};
					dwForm.shipvoyageName = feature.get("shipvoyageName");
          dwForm.cargoOwnerName = feature.get("cargoOwnerName");
          dwForm.cargoAgentName = feature.get("cargoAgentName");
					dwForm.cargoName = feature.get("cargoName");
					dwForm.quantity = feature.get("quantity");
					dwForm.volume = feature.get("volume");
					dwForm.ton = feature.get("ton");
					_this.dwForm = dwForm;

					//创建弹出框
					overlay = new Overlay({
						element: dw_container,
					});

          _this.dwTableStyle.display = 'block'
					overlay.setPosition(coordinate);
					this.addOverlay(overlay);
				}
      })
    },
    // 获取票货
    getCargoInfo () {
      publicapi.getDivideVotes().then(res => {
        this.cargoInfoList = res.data.data
      })
    },
    // 获取库场
    getstorehouseList () {
      publicapi.listStorehouse().then(res => {
        this.storehouseList = res.data.data
      })
    },
    // 通过库场获取货位/垛号
    getLocationAndStackByid (value) {
      this.getLocation(value)
      this.getStackPosition(value)
    },
    // 通过库场id获取货位
    getLocation (val) {
      this.editForm.locationId = ''
      this.locationList = []
      publicapi.getStorehouseLocation(val).then(res => {
        this.locationList = res.data.data
      })
    },
    // 通过库场id获取垛号
    getStackPosition (val) {
      let params = {
        storehouseId: val,
        locationId:'',
        cargoInfoId: this.editForm.cargoInfoId?this.cargoInfoList.filter(v => v.id == this.editForm.cargoInfoId)[0].cargoInfoId:''
      }
      this.editForm.stackPosition = ''
      this.heapList = []
      api.queryStackPosition(params).then(res => {
        this.heapList = res.data.data
      })
    },
    // 通过货位id获取垛号
    getStackPositionByid (val) {
      let params = {
        storehouseId: this.editForm.storehouseId,
        locationId: val,
        cargoInfoId: this.editForm.cargoInfoId?this.cargoInfoList.filter(v => v.id == this.editForm.cargoInfoId)[0].cargoInfoId:''
      }
      api.queryStackPosition(params).then(res => {
        this.heapList = res.data.data
      })
    },
    // 确认绘制信息
    submitDrawer () {
      this.$refs.formName.validate((valid) => {
        if (!valid) {
          return false
        }
        this.doEntry()
      })
    },
    // 绘制库场
    doEntry () {
      let _this = this;
      this.dialogVisible = false;
      let coordinate = new Array();
      // 添加一个绘制的线使用的layer
      let lineLayer = new VectorLayer({
        source: new VectorSource(),
        style: new Style({
          stroke: new Stroke({
            color: 'red',
            size: 1
          })
        })
      });
      this.map.addLayer(lineLayer);
      //画线时的样式
      let lineDraw = new Draw({
        source: lineLayer.getSource(),
        type: 'Polygon',
        maxPoints: 4,    // 限制不超过4个点
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2
          }),
          image: new CircleStyle({
            radius: 3,
            fill: new Fill({
              color: '#ffcc33'
            })
          })
        })
      });
      // 监听线绘制结束事件，获取坐标
      lineDraw.on('drawend', function (event) {
        coordinate = event.feature.getGeometry().getCoordinates();
          let points = coordinate[0];

          let coordinateList = points.toString().split(",");

          //清除多余的点坐标
          let first = coordinateList[0]
          let second = coordinateList[1]
          let second_to_last = coordinateList[coordinateList.length - 2]
          let last_one = coordinateList[coordinateList.length - 1]
          if (first === second_to_last && second === last_one) {
              coordinateList.length = coordinateList.length - 2
          }

          let lon1 = '';
          let lat1 = '';
          let lon2 = '';
          let lat2 = '';
          let lon3 = '';
          let lat3 = '';
          let lon4 = '';
          let lat4 = '';
          let lon5 = '';
          let lat5 = '';
          let lon6 = '';
          let lat6 = '';

          for (let i = 0; i < coordinateList.length; i++) {
            let coordinate = coordinateList[i];
            switch (i) {
              case 0:
                lon1 = coordinate;
                break;
              case 1:
                lat1 = coordinate;
                break;
              case 2:
                lon2 = coordinate;
                break;
              case 3:
                lat2 = coordinate;
                break;
              case 4:
                lon3 = coordinate;
                break;
              case 5:
                lat3 = coordinate;
                break;
              case 6:
                lon4 = coordinate;
                break;
              case 7:
                lat4 = coordinate;
                break;
              case 8:
                lon5 = coordinate;
                break;
              case 9:
                lat5 = coordinate;
                break;
              case 10:
                lon6 = coordinate;
                break;
              case 11:
                lat6 = coordinate;
            }
          }

          //修改数据库
          api.insert({
              "cargoInfoId": _this.heapList.filter(v => v.stackPosition == _this.editForm.stackPosition)[0].cargoInfoId,
              "storehouseId": _this.editForm.storehouseId,
              "storehouseName": _this.storehouseList.filter(e => e.id == _this.editForm.storehouseId)[0].storehouseName,
              "locationId": _this.editForm.locationId,
              "locationNo": _this.editForm.locationId?_this.locationList.filter(v => v.locationId == _this.editForm.locationId)[0].locationNo:'',
              "stackPosition": _this.editForm.stackPosition,
              "lon1": lon1,
              "lat1": lat1,
              "lon2": lon2,
              "lat2": lat2,
              "lon3": lon3,
              "lat3": lat3,
              "lon4": lon4,
              "lat4": lat4,
              "lon5": lon5,
              "lat5": lat5,
              "lon6": lon6,
              "lat6": lat6,
          }).then(res => {
            let e = res.data

            if (e.code !== '0000') {
              _this.$message.error(e.msg);
            } else {
              _this.$message.success("绘制完成");
              _this.getDrawerStorehouse()
            }
          })
          _this.map.removeLayer(lineLayer);
          _this.map.removeInteraction(lineDraw);

          //取消绘制围栏时使用
          _this.map.removeInteraction(lineDraw);
      });
      this.map.addInteraction(lineDraw);
    },
    // 获取绘制库场信息
    getDrawerStorehouse () {
      api.queryAll().then(res => {
        this.heapNameList = res.data.data
        this.showHeapList()
      })
    },
    //显示库场
    showHeapList() {
      if (this.massLayerHeap) {
        this.map.removeLayer(this.massLayerHeap);
      }
      console.log(this.heapNameList)
        
      //存储货位Feature的数组
      let massFeatureArray = new Array();
      let imgFeatureArray = new Array();
      for (let i = 0; i < this.heapNameList.length; i++) {
        let ponits = new Array();
        let point1 = [parseFloat(this.heapNameList[i].lon1), parseFloat(this.heapNameList[i].lat1)];
        ponits.push(point1);

        let point2 = [parseFloat(this.heapNameList[i].lon2), parseFloat(this.heapNameList[i].lat2)];
        ponits.push(point2);

        let point3 = [parseFloat(this.heapNameList[i].lon3), parseFloat(this.heapNameList[i].lat3)];
        ponits.push(point3);

        if (this.heapNameList[i].lon4 != "" && this.heapNameList[i].lon4 != null) {
          let point4 = [parseFloat(this.heapNameList[i].lon4), parseFloat(this.heapNameList[i].lat4)];
          ponits.push(point4);
        }

        if (this.heapNameList[i].lon5 != "" && this.heapNameList[i].lon5 != null) {
          let point5 = [parseFloat(this.heapNameList[i].lon5), parseFloat(this.heapNameList[i].lat5)];
          ponits.push(point5);
        }

        if (this.heapNameList[i].lon6 != "" && this.heapNameList[i].lon6 != null) {
          let point6 = [parseFloat(this.heapNameList[i].lon6), parseFloat(this.heapNameList[i].lat6)];
          ponits.push(point6);
        }
            
        let lon1 = Number(this.heapNameList[i].lon1)
        let lon2 = Number(this.heapNameList[i].lon2)
        let lon3 = Number(this.heapNameList[i].lon3)
        let lon4 = Number(this.heapNameList[i].lon4)
        let lat1 = Number(this.heapNameList[i].lat1)
        let lat2 = Number(this.heapNameList[i].lat2)
        let lat3 = Number(this.heapNameList[i].lat3)
        let lat4 = Number(this.heapNameList[i].lat4)
    
        let lon = (lon1 + lon2 + lon3 + lon4) / 4
        let lat = (lat1 + lat2 + lat3 + lat4) / 4

        // fix: modify无法对第一个点和最后一个点之间的线段进行修改。
        let point_last = [parseFloat(this.heapNameList[i].lon1), parseFloat(this.heapNameList[i].lat1)];
        ponits.push(point_last);

        let polygonFeature = new Feature(
          new Polygon([ponits])
        );
        //垛位样式
        let polygonStyle = new Style({
          stroke: new Stroke({
            color: '#A7AAB5',
            width: 1
          }),
          fill: new Fill({
            color: this.heapNameList[i].cargoColor
          }),
          text: new Text({
            font: '12px Calibri,sans-serif',
            text: this.heapNameList[i].stackPosition,//在垛位上显示垛位名称
            fill: new Fill({
                color: 'white'
            })
          })
        });
        polygonFeature.setStyle(polygonStyle);
        polygonFeature.set("id", this.heapNameList[i].id);
        polygonFeature.set("showType", "storehouse");
        polygonFeature.set("storehouseId", this.heapNameList[i].storehouseId);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("cargoInfoId", this.heapNameList[i].cargoInfoId);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("stackPosition", this.heapNameList[i].stackPosition);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("shipvoyageName", this.heapNameList[i].shipvoyageName);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("cargoOwnerName", this.heapNameList[i].cargoOwnerName);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("cargoAgentName", this.heapNameList[i].cargoAgentName);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("cargoName", this.heapNameList[i].cargoName);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("quantity", this.heapNameList[i].quantity);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("ton", this.heapNameList[i].ton);//点击在popup弹出框中显示垛位具体信息
        polygonFeature.set("volume", this.heapNameList[i].volume);//点击在popup弹出框中显示垛位具体信息

        massFeatureArray.push(polygonFeature);
        imgFeatureArray.push(polygonFeature);
      }
      this.massLayerHeap = new VectorLayer({
        source: new VectorSource({
          features: massFeatureArray,
        }),
        zIndex: 90,
      });

      this.map.addLayer(this.massLayerHeap);
    },
    // 显示名称
    showHeapName () {
      
      return '2'
    },
    // 删除库场
    deleteStorehouse () {
      let params = {
        id: this.feature.values_.id
      }
      api.deleteById(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.data.msg)
        }
        this.$message.success('删除成功')
        this.getDrawerStorehouse()
      })
    },
    // 获取机械
    getMachine () {
      api.queryTGpsEquipment().then(res => {
        this.machineList = res.data.data
        this.showMachineInfo()
      })
    },
    // 显示机械位置信息
    showMachineInfo () {
      if (this.miVectorLayer) {
				this.map.removeLayer(this.miVectorLayer);
			}

			let vectorSource = new VectorSource({
				//features: [polygonFeature],
			});
			this.miVectorLayer = new VectorLayer({
				source: vectorSource,
				zIndex: 2,
			});
			let polygonFeature;
			for (let i = 0; i < this.machineList.length; i++) {
				let lon = this.machineList[i].lon;
				let lat = this.machineList[i].lat;

				polygonFeature = new Feature({
					geometry: new Point([lon, lat]),
				});

				//样式
				let machineStyle = new Style({
					image: new Icon({
						src: this.machineLogo,
						scale: 0.7,
					}),
					text: new Text({
						font: "12px Calibri,sans-serif",
						text: this.machineList[i].equipmentNo,
            offsetY: -18,
						fill: new Fill({
							color: "blue",
						}),
					}),
				});

				polygonFeature.setStyle(machineStyle);
				polygonFeature.set("showType", "machineInfo");
				polygonFeature.set("planId", this.machineList[i].planId);
				polygonFeature.set("equipmentId", this.machineList[i].equipmentId);
				polygonFeature.set("equipmentNo", this.machineList[i].equipmentNo);
				polygonFeature.set("speed", this.machineList[i].speed);
				polygonFeature.set("derection", this.machineList[i].derection);

				polygonFeature.setId(this.machineList[i].id);
				vectorSource.addFeature(polygonFeature);
			}
			this.map.addLayer(this.miVectorLayer);
    },
  },
  
}
</script>
<style lang="less" scoped>
@import "./index.less";

</style>